const express = require('express');
const { PasswordSecurity, TokenManager, InputSecurity } = require('../security');
const { ExceptionHandler } = require('../consistency');
const { PerformanceMonitor } = require('../performance');
const User = require('../models/User');
const MessageQueueClient = require('../common/message-queue-client');
const EventBus = require('../common/event-bus');
const ServiceDiscovery = require('../common/service-discovery');
const ConfigCenter = require('../common/config-center');
const TracingService = require('../common/tracing-service');
const SagaOrchestrator = require('../common/saga-orchestrator');

class EnhancedUserService {
    constructor() {
        this.app = express();
        this.port = process.env.USER_SERVICE_PORT || 3001;
        this.serviceName = 'user-service';
        
        // 初始化组件
        this.exceptionHandler = new ExceptionHandler();
        this.performanceMonitor = new PerformanceMonitor();
        
        // 初始化新架构组件
        this.initializeComponents();
        
        this.setupMiddleware();
        this.setupRoutes();
        this.setupHealthCheck();
        this.setupEventHandlers();
    }

    async initializeComponents() {
        // 初始化消息队列
        this.messageQueueClient = new MessageQueueClient({
            url: process.env.RABBITMQ_URL || 'amqp://localhost:5672',
            prefetchCount: 10
        });
        
        // 初始化事件总线
        this.eventBus = new EventBus({
            url: process.env.RABBITMQ_URL || 'amqp://localhost:5672',
            exchangeName: 'user.events'
        });
        
        // 初始化服务发现
        this.serviceDiscovery = new ServiceDiscovery({
            host: process.env.CONSUL_HOST || 'localhost',
            port: process.env.CONSUL_PORT || 8500
        });
        
        // 初始化配置中心
        this.configCenter = new ConfigCenter({
            hosts: process.env.ETCD_HOSTS?.split(',') || ['localhost:2379']
        });
        
        // 初始化链路追踪
        this.tracingService = new TracingService({
            serviceName: this.serviceName,
            agentHost: process.env.JAEGER_AGENT_HOST || 'localhost',
            agentPort: process.env.JAEGER_AGENT_PORT || 6831
        });
        
        // 初始化Saga编排器
        this.sagaOrchestrator = new SagaOrchestrator({
            timeout: 60000,
            retryAttempts: 3
        });
        
        // 等待所有组件初始化完成
        await Promise.all([
            this.messageQueueClient.connect(),
            this.eventBus.init(),
            this.configCenter.init()
        ]);
        
        console.log('All components initialized for user service');
    }

    setupMiddleware() {
        this.app.use(express.json({ limit: '1mb' }));
        this.app.use(express.urlencoded({ extended: true }));
        
        // 性能监控
        this.app.use((req, res, next) => {
            const startTime = Date.now();
            res.on('finish', () => {
                const responseTime = Date.now() - startTime;
                this.performanceMonitor.recordRequest(req.path, req.method, responseTime, res.statusCode);
            });
            next();
        });
        
        // 链路追踪中间件
        this.app.use(this.tracingService.createMiddleware());
    }

    setupRoutes() {
        // 用户注册
        this.app.post('/register', this.tracingService.wrapFunction(async (req, res) => {
            const span = req.span;
            
            try {
                const { username, email, password, role = 'user' } = req.body;
                
                // 输入验证
                if (!username || !email || !password) {
                    return res.status(400).json({ 
                        success: false, 
                        message: '用户名、邮箱和密码为必填项' 
                    });
                }
                
                if (!InputSecurity.validateEmail(email)) {
                    return res.status(400).json({ 
                        success: false, 
                        message: '邮箱格式不正确' 
                    });
                }
                
                // 记录事件
                this.tracingService.logEvent(span, 'user_registration_started', {
                    username,
                    email
                });
                
                // 创建用户Saga
                const sagaId = await this.createUserSaga(username, email, password, role);
                
                // 获取Saga结果
                const saga = this.sagaOrchestrator.getSaga(sagaId);
                
                if (saga.status === 'completed') {
                    // 发布用户注册事件
                    await this.eventBus.publish('user.registered', {
                        userId: saga.data.userId,
                        username,
                        email,
                        role,
                        registeredAt: new Date().toISOString()
                    });
                    
                    this.tracingService.logEvent(span, 'user_registration_completed', {
                        userId: saga.data.userId
                    });
                    
                    res.status(201).json({
                        success: true,
                        message: '用户注册成功',
                        data: {
                            userId: saga.data.userId,
                            username,
                            email,
                            role
                        }
                    });
                } else {
                    this.tracingService.logEvent(span, 'user_registration_failed', {
                        error: saga.error?.message
                    });
                    
                    res.status(500).json({
                        success: false,
                        message: '用户注册失败',
                        error: saga.error?.message
                    });
                }
            } catch (error) {
                this.tracingService.logEvent(span, 'user_registration_error', {
                    error: error.message
                });
                
                this.exceptionHandler.handleError(error, 'user.register');
                res.status(500).json({
                    success: false,
                    message: '服务器内部错误'
                });
            }
        }, 'user.register'));
        
        // 用户登录
        this.app.post('/login', this.tracingService.wrapFunction(async (req, res) => {
            const span = req.span;
            
            try {
                const { email, password } = req.body;
                
                // 输入验证
                if (!email || !password) {
                    return res.status(400).json({ 
                        success: false, 
                        message: '邮箱和密码为必填项' 
                    });
                }
                
                // 记录事件
                this.tracingService.logEvent(span, 'user_login_attempt', {
                    email
                });
                
                // 查找用户
                const user = await User.findByEmail(email);
                
                if (!user) {
                    this.tracingService.logEvent(span, 'user_login_failed', {
                        email,
                        reason: 'user_not_found'
                    });
                    
                    return res.status(401).json({
                        success: false,
                        message: '邮箱或密码错误'
                    });
                }
                
                // 验证密码
                const isPasswordValid = await PasswordSecurity.verifyPassword(password, user.password);
                
                if (!isPasswordValid) {
                    this.tracingService.logEvent(span, 'user_login_failed', {
                        email,
                        reason: 'invalid_password'
                    });
                    
                    return res.status(401).json({
                        success: false,
                        message: '邮箱或密码错误'
                    });
                }
                
                // 生成JWT令牌
                const token = TokenManager.generateToken({
                    userId: user.id,
                    email: user.email,
                    role: user.role
                });
                
                // 更新最后登录时间
                await User.updateLastLogin(user.id);
                
                // 发布用户登录事件
                await this.eventBus.publish('user.logged_in', {
                    userId: user.id,
                    email: user.email,
                    loginTime: new Date().toISOString()
                });
                
                this.tracingService.logEvent(span, 'user_login_success', {
                    userId: user.id,
                    email
                });
                
                res.json({
                    success: true,
                    message: '登录成功',
                    data: {
                        token,
                        user: {
                            id: user.id,
                            username: user.username,
                            email: user.email,
                            role: user.role
                        }
                    }
                });
            } catch (error) {
                this.tracingService.logEvent(span, 'user_login_error', {
                    error: error.message
                });
                
                this.exceptionHandler.handleError(error, 'user.login');
                res.status(500).json({
                    success: false,
                    message: '服务器内部错误'
                });
            }
        }, 'user.login'));
        
        // 获取用户信息
        this.app.get('/users/:id', this.tracingService.wrapFunction(async (req, res) => {
            const span = req.span;
            
            try {
                const userId = req.params.id;
                
                // 记录事件
                this.tracingService.logEvent(span, 'user_profile_request', {
                    userId
                });
                
                // 查找用户
                const user = await User.findById(userId);
                
                if (!user) {
                    this.tracingService.logEvent(span, 'user_profile_not_found', {
                        userId
                    });
                    
                    return res.status(404).json({
                        success: false,
                        message: '用户不存在'
                    });
                }
                
                this.tracingService.logEvent(span, 'user_profile_retrieved', {
                    userId
                });
                
                res.json({
                    success: true,
                    data: {
                        id: user.id,
                        username: user.username,
                        email: user.email,
                        role: user.role,
                        createdAt: user.createdAt,
                        lastLogin: user.lastLogin
                    }
                });
            } catch (error) {
                this.tracingService.logEvent(span, 'user_profile_error', {
                    error: error.message
                });
                
                this.exceptionHandler.handleError(error, 'user.getProfile');
                res.status(500).json({
                    success: false,
                    message: '服务器内部错误'
                });
            }
        }, 'user.getProfile'));
        
        // 更新用户信息
        this.app.put('/users/:id', this.tracingService.wrapFunction(async (req, res) => {
            const span = req.span;
            
            try {
                const userId = req.params.id;
                const { username, email, role } = req.body;
                
                // 记录事件
                this.tracingService.logEvent(span, 'user_update_started', {
                    userId
                });
                
                // 查找用户
                const user = await User.findById(userId);
                
                if (!user) {
                    this.tracingService.logEvent(span, 'user_update_failed', {
                        userId,
                        reason: 'user_not_found'
                    });
                    
                    return res.status(404).json({
                        success: false,
                        message: '用户不存在'
                    });
                }
                
                // 保存旧数据
                const oldData = {
                    username: user.username,
                    email: user.email,
                    role: user.role
                };
                
                // 更新用户信息
                const updatedUser = await User.update(userId, {
                    username: username || user.username,
                    email: email || user.email,
                    role: role || user.role
                });
                
                // 发布用户更新事件
                await this.eventBus.publish('user.updated', {
                    userId: updatedUser.id,
                    oldData,
                    newData: {
                        username: updatedUser.username,
                        email: updatedUser.email,
                        role: updatedUser.role
                    },
                    updatedAt: updatedUser.updatedAt
                });
                
                this.tracingService.logEvent(span, 'user_update_completed', {
                    userId
                });
                
                res.json({
                    success: true,
                    message: '用户信息更新成功',
                    data: {
                        id: updatedUser.id,
                        username: updatedUser.username,
                        email: updatedUser.email,
                        role: updatedUser.role,
                        updatedAt: updatedUser.updatedAt
                    }
                });
            } catch (error) {
                this.tracingService.logEvent(span, 'user_update_error', {
                    error: error.message
                });
                
                this.exceptionHandler.handleError(error, 'user.update');
                res.status(500).json({
                    success: false,
                    message: '服务器内部错误'
                });
            }
        }, 'user.update'));
        
        // 删除用户
        this.app.delete('/users/:id', this.tracingService.wrapFunction(async (req, res) => {
            const span = req.span;
            
            try {
                const userId = req.params.id;
                
                // 记录事件
                this.tracingService.logEvent(span, 'user_deletion_started', {
                    userId
                });
                
                // 查找用户
                const user = await User.findById(userId);
                
                if (!user) {
                    this.tracingService.logEvent(span, 'user_deletion_failed', {
                        userId,
                        reason: 'user_not_found'
                    });
                    
                    return res.status(404).json({
                        success: false,
                        message: '用户不存在'
                    });
                }
                
                // 删除用户
                await User.delete(userId);
                
                // 发布用户删除事件
                await this.eventBus.publish('user.deleted', {
                    userId: user.id,
                    username: user.username,
                    email: user.email,
                    deletedAt: new Date().toISOString()
                });
                
                this.tracingService.logEvent(span, 'user_deletion_completed', {
                    userId
                });
                
                res.json({
                    success: true,
                    message: '用户删除成功'
                });
            } catch (error) {
                this.tracingService.logEvent(span, 'user_deletion_error', {
                    error: error.message
                });
                
                this.exceptionHandler.handleError(error, 'user.delete');
                res.status(500).json({
                    success: false,
                    message: '服务器内部错误'
                });
            }
        }, 'user.delete'));
    }

    // 创建用户Saga
    async createUserSaga(username, email, password, role) {
        const sagaId = this.sagaOrchestrator.createSaga('user_creation', {
            username,
            email,
            password,
            role
        });
        
        // 添加步骤1: 验证输入
        this.sagaOrchestrator.addStep(sagaId, async (data) => {
            // 验证用户名是否已存在
            const existingUser = await User.findByUsername(data.username);
            if (existingUser) {
                throw new Error('用户名已存在');
            }
            
            // 验证邮箱是否已存在
            const existingEmail = await User.findByEmail(data.email);
            if (existingEmail) {
                throw new Error('邮箱已存在');
            }
            
            return { validated: true };
        }, async (data, result) => {
            // 补偿操作：无需补偿
            console.log('Step 1 compensation: No action needed');
        });
        
        // 添加步骤2: 加密密码
        this.sagaOrchestrator.addStep(sagaId, async (data) => {
            const hashedPassword = await PasswordSecurity.hashPassword(data.password);
            return { hashedPassword };
        }, async (data, result) => {
            // 补偿操作：无需补偿
            console.log('Step 2 compensation: No action needed');
        });
        
        // 添加步骤3: 创建用户
        this.sagaOrchestrator.addStep(sagaId, async (data) => {
            const user = await User.create({
                username: data.username,
                email: data.email,
                password: data.hashedPassword,
                role: data.role
            });
            
            return { userId: user.id };
        }, async (data, result) => {
            // 补偿操作：删除用户
            if (result && result.userId) {
                await User.delete(result.userId);
                console.log(`Step 3 compensation: Deleted user ${result.userId}`);
            }
        });
        
        // 执行Saga
        this.sagaOrchestrator.execute(sagaId);
        
        return sagaId;
    }

    setupHealthCheck() {
        this.app.get('/health', (req, res) => {
            res.json({
                status: 'healthy',
                service: this.serviceName,
                timestamp: new Date().toISOString(),
                uptime: process.uptime()
            });
        });
    }

    setupEventHandlers() {
        // 监听配置变化
        this.configCenter.on('configChanged', ({ key, value }) => {
            console.log(`Config changed for user service: ${key} = ${JSON.stringify(value)}`);
            
            // 如果是用户服务配置，更新服务设置
            if (key.startsWith('user-service.')) {
                this.updateServiceConfig(key, value);
            }
        });
        
        // 监听其他服务的事件
        this.eventBus.subscribe('order.created', async (event, context) => {
            // 处理订单创建事件，可能需要更新用户信息
            console.log(`Order created event received: ${event.data.orderId}`);
            
            // 可以在这里更新用户的订单统计等信息
            // await User.updateOrderStats(event.data.userId);
        });
        
        // 监听Saga事件
        this.sagaOrchestrator.on('sagaCompleted', ({ sagaId, sagaType }) => {
            console.log(`Saga completed in user service: ${sagaId} (${sagaType})`);
        });
        
        this.sagaOrchestrator.on('sagaAborted', ({ sagaId, sagaType, error }) => {
            console.error(`Saga aborted in user service: ${sagaId} (${sagaType}) - ${error.message}`);
        });
    }

    // 更新服务配置
    updateServiceConfig(key, value) {
        switch (key) {
            case 'user-service.password.min_length':
                // 更新密码最小长度配置
                break;
            case 'user-service.session.timeout':
                // 更新会话超时配置
                break;
            // 其他配置项...
        }
    }

    // 启动服务
    async start() {
        // 注册服务
        await this.serviceDiscovery.registerService(
            this.serviceName,
            `${this.serviceName}-${process.env.HOSTNAME || 'local'}`,
            '0.0.0.0',
            this.port,
            {
                tags: ['user', 'auth'],
                healthPath: '/health'
            }
        );
        
        return this.app.listen(this.port, () => {
            console.log(`🚀 Enhanced User Service running on port ${this.port}`);
            console.log(`🔗 Service discovery enabled`);
            console.log(`📊 Event bus connected`);
            console.log(`🔧 Config center connected`);
            console.log(`🔍 Distributed tracing enabled`);
            console.log(`🔄 Saga orchestrator enabled`);
        });
    }

    // 关闭服务
    async close() {
        // 关闭所有组件
        await this.messageQueueClient.close();
        await this.eventBus.close();
        await this.configCenter.close();
        this.tracingService.close();
        
        console.log('Enhanced User Service closed');
    }
}

module.exports = EnhancedUserService;